package com.yangmf.auto_message_handle.utils;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yangmf.auto_message_handle.pojo.entity.DeepSeekRequestModel;
import com.yangmf.auto_message_handle.properties.DeskProperties;
import jakarta.annotation.PostConstruct;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.net.ssl.*;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

@Component
public class Deskutil {

    @Autowired
    private DeskProperties deskConfig;

    @PostConstruct
    public void init() {
        if (deskConfig != null) {
            this.API_URL = deskConfig.getUrl();
            this.apiKey = deskConfig.getKey();
            // 其他初始化逻辑
        }
    }

    /**
     * 请求API地址
     */
    private static String API_URL;
    /**
     * 你在DeepSeek官网申请的API KEY，注意不要泄露给他人！
     */
    private static String apiKey;

    // 默认超时时间（毫秒）
    private static final int DEFAULT_TIMEOUT = 30000;

    // 默认重试次数
    private static final int DEFAULT_MAX_RETRIES = 3;

    public String getResponse(String prompt) throws IOException {
        return getResponse(prompt, DEFAULT_TIMEOUT, DEFAULT_MAX_RETRIES);
    }

    public String getResponse(String prompt, int timeoutMillis) throws IOException {
        return getResponse(prompt, timeoutMillis, DEFAULT_MAX_RETRIES);
    }

    public String getResponse(String prompt, int timeoutMillis, int maxRetries) throws IOException {
        IOException lastException = null;

        for (int attempt = 0; attempt <= maxRetries; attempt++) {
            try {
                // 构建带证书信任的 OkHttpClient
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(timeoutMillis, TimeUnit.MILLISECONDS)
                        .readTimeout(timeoutMillis, TimeUnit.MILLISECONDS)
                        .writeTimeout(timeoutMillis, TimeUnit.MILLISECONDS)
                        .sslSocketFactory(createTrustAllSSLContext().getSocketFactory(), createTrustAllTrustManager())
                        .hostnameVerifier((hostname, session) -> true)
                        .build();

                // 构建请求体
                DeepSeekRequestModel.Message message = DeepSeekRequestModel.Message.builder()
                        .role("user")
                        .content(prompt).build();
                DeepSeekRequestModel requestBody = DeepSeekRequestModel.builder()
                        .model("deepseek-chat")
                        .messages(Collections.singletonList(message))
                        .build();

                // 构建请求体json：{"messages":[{"content":"你好，DeepSeek！","role":"user"}],"model":"deepseek-chat"}
                String jsonBody = JSON.toJSONString(requestBody);
                // 创建HTTP请求
                Request request = new Request.Builder()
                        .url(API_URL)
                        .post(RequestBody.create(jsonBody, MediaType.get("application/json")))
                        .addHeader("Authorization", "Bearer " + apiKey)
                        .build();

                // 发送请求并处理响应
                try (Response response = client.newCall(request).execute()) {
                    // 如果响应成功，并且返回体有内容，就输出内容，否则表示响应失败
                    if (response.isSuccessful() && response.body() != null) {
                        String responseBody = response.body().string();
                        ObjectMapper objectMapper = new ObjectMapper();
                        JsonNode jsonNode = objectMapper.readTree(responseBody);
                        return jsonNode.get("choices").get(0).get("message").get("content").toString();
                    }
                    throw new IOException("Unexpected code " + response);
                }
            } catch (SocketTimeoutException e) {
                lastException = e;
                // 如果不是最后一次重试，则等待后重试
                if (attempt < maxRetries) {
                    try {
                        // 等待一段时间后重试，递增等待时间
                        Thread.sleep(1000 * (attempt + 1));
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                        throw new IOException("Interrupted during retry", ie);
                    }
                }
            }
        }

        // 所有重试都失败后抛出异常
        throw new IOException("Failed after " + maxRetries + " retries", lastException);
    }

    // 创建信任所有证书的SSL上下文
    private SSLContext createTrustAllSSLContext() throws IOException {
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{createTrustAllTrustManager()}, new SecureRandom());
            return sslContext;
        } catch (Exception e) {
            throw new IOException("Failed to create trust all SSL context", e);
        }
    }

    // 创建信任所有证书的信任管理器
    private X509TrustManager createTrustAllTrustManager() {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
                // 信任所有客户端证书
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
                // 信任所有服务器证书
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
    }
}
